import {
	WEB_VIEW_TYPE,
} from '@/const/index';
import envVersion from '@/envVersion.js';
/**
 * 判断是否为空
 */
import dayjs from 'dayjs';
export const isEmpty = (val) => {
	if (typeof val === 'undefined' || val === null || val === '') {
		return true;
	}
	if (Array.isArray(val)) {
		return val.length === 0;
	}
	if (typeof val === 'object') {
		return Object.keys(val).length === 0;
	}
	return false;
};

// 判断是否为外部链接
export const isExternalLinks = (url) => {
	return /(http|https):\/\//i.test(url);
};

/**
 * 获取Url的query参数
 */
export const getQueryParams = (url = window.location.href) => {
	const params = {};
	const paramsStr = url.substring(url.lastIndexOf('?') + 1);
	const paramsArr = paramsStr.split('&');
	paramsArr.forEach((item) => {
		const [key, value] = item.split('=');
		params[key] = value;
	});
	return params;
};

/**
 * 参数对象转换为query字符串
 */
export const paramsToQueryStr = (params) => {
	const paramsArr = [];
	Object.keys(params).forEach((key) => {
		paramsArr.push(`${key}=${params[key]}`);
	});
	return paramsArr.join('&');
};

/**
 * 去除Url里的token参数
 */
export const filtUrlToken = (url = window.location.href) => {
	const params = getQueryParams(url);
	if (params.token) {
		delete params.token;
		return `${url.substring(0, url.lastIndexOf('?'))}?${paramsToQueryStr(params)}`;
	}
	return url;
};

/**
 * 将图片URL转为Base64(本地加载线上图片有问题)
 */
export const image2Base64 = (url, callback) => {
	const img = new Image();
	img.setAttribute('crossOrigin', 'anonymous');
	img.src = url;
	img.onload = () => {
		const canvas = document.createElement('canvas');
		canvas.width = img.width;
		canvas.height = img.height;
		const ctx = canvas.getContext('2d');
		ctx.drawImage(img, 0, 0, img.width, img.height);
		const base64 = canvas.toDataURL('image/png');
		callback(base64);
	};
};

/**
 * 将字符串里的${}替换为对象里的值，并且在'${'前加上前缀，'}'后加上后缀
 * .e.g:
 * str:  "您本次捐赠金额￥${donateAmount}，可以让${catQty}只流浪猫饱餐1顿。"
 * obj: {catQty: 0.02, donateAmount: 0.03}
 * @returns '您本次捐赠金额￥0.03，可以让0.02只流浪猫饱餐1顿。'
 */
export const replaceTemplate = (str, obj, preffix = '', suffix = '') => {
	if (!str) return '';
	const reg = /\$\{(\w+)\}/g;
	return str.replace(reg, (match, key) => {
		return preffix + obj[key] + suffix;
	});
};

export const subStringName = (name, length = 8) => {
	return name.substring(0, name.length > length ? length : name.length);
};

export const likeCountFilters = (num) => {
	console.log('nnnn', num);
	if (num === null || num === '') {
		num = '0';
	} else if (num > 9999) {
		num = parseFloat(num / 10000).toFixed('1') + '万';
	} else if (num > 1000000) {
		num = '100万+';
	}
	return num;
};
/**
 * 跳转到web-view页面
 */
export const navigateToWebView = ({
	url,
	type,
	title,
}) => {
	let path;
	if (type === WEB_VIEW_TYPE.PET) {
		path = envVersion.h5PetUrl;
		path = encodeURIComponent(path + url);
	} else if (type === WEB_VIEW_TYPE.SHOP) {
		path = envVersion.h5ShopUrl;
		path = encodeURIComponent(path + '/#' + url);
	}

	uni.navigateTo({
		url: `/pages/web-view/index?path=${path}&title=${title}`,
	});
};

export const replaceCloudAdoptTemplate = (
	str,
	obj,
	preffix = '',
	suffix = '',
	style = '') => {
	if (!str) return '';
	const reg = /\$\{(\w+)\}/g;
	return str.replace(reg, (match, key) => {
		if (key === 'cloudAdoptAreaName') {
			return style + obj[key] + suffix;
		}
		if (key === 'catNickName') {
			return preffix + obj[key] + suffix;
		}
		return `<span>${obj[key]}${suffix}`;
	});
};

export const formatToDate = (date, format = 'YYYY-MM-DD') => {
	return dayjs(date).format(format);
};
//播放云养音频
export const playAdoptAudio = () => {
	const innerAudioContext = uni.createInnerAudioContext();
	console.log('innerAudioContext', innerAudioContext);
	innerAudioContext.src =
		'https://cdn-prod.findapet.com.cn/cloud_adopt_muyu.mp3';
	innerAudioContext.volume = 1;
	innerAudioContext.play();
	innerAudioContext.onError((res) => {
		console.log(res.errMsg);
		console.log(res.errCode);
	});
};

export const replaceCloudAdoptRights = (content) => {
	return content.replace(/\n/g, '<br>');
};